import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Route, Switch, Link, Redirect} from 'react-router-dom'
import routes from './router.js'
import * as mobx from 'mobx'
// import { connect } from 'react-redux'
// import { collapseAction } from './redux/actions'
import { observer , inject} from 'mobx-react'
import './App.css'
import { Modal, Layout, Menu, Icon, message, Button, LocaleProvider, Dropdown, Spin } from 'antd'
import enUS from 'antd/lib/locale-provider/en_US'
import 'react-quill/dist/quill.snow.css'
const {SubMenu} = Menu
const {Header, Content, Sider} = Layout
const confirm = Modal.confirm

const localeFn = (WrappedComponent) => {
  @inject('store','itemStore')@observer
  class myComponent extends Component {
    static contextTypes = {
      store: PropTypes.object,
    }
    render(){
      // const { store } = this.context
      const v = this.props.store.locale.key === 'en' ? enUS: null
      return (<LocaleProvider locale={v}><WrappedComponent {...this.props}/></LocaleProvider>)
    } 
  }
  return myComponent
}
@observer
class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      selectedMenu: [],
      openMenu: [],
      localeKey: 'zh',
      shopName: '全部',
      currentModule: '',
      moduleId: '',
      hasHelpMessage: false,
      visible: false
    }
  }

  static contextTypes = {
    store: PropTypes.object,
  }

  componentWillMount() {
    this.props.store.initMenu();
  }

  componentDidMount () {
    const session = JSON.parse(window.localStorage.getItem("riderMain"));
    const {menu} = this.props.store;
    let currPath = this.props.location.pathname;
    let {openKey, ifSub} = this.changeMenu(currPath)
    if(session &&  window.location.hash !== '#/login') {
      const user = session.UserId;
      if(user) {
        this.props.store.getMenu(user);
      }
    }
    if(menu[0]) {
      if(menu[0].children && menu[0].children[0]) {
        currPath = menu[0].children[0].url
      } else {
        currPath = menu[0].url
      }
      this.props.history.push(currPath);
    }
    if(currPath.indexOf('/item/modify') !== -1) {
      this.setState({
        selectedMenu: ['/item/schedule'],
        openMenu: ['item']
      })
    } else if(currPath.indexOf('/store/item/') !== -1) {
      this.setState({
        selectedMenu: ['/store/item'],
        openMenu: ['item']
      })
    } else {
      this.setState({
        selectedMenu: [currPath],
        openMenu: []
      })
      if (ifSub) {
        this.setState({
          openMenu: openKey
        })
      }
    }
  }

  componentWillReceiveProps = (nextProps) => {
    let next = nextProps.location.pathname
    let curr = this.props.location.pathname
    //let {openKey, ifSub} = this.changeMenu(next)
    const { openMenu } = this.state;
    if (next !== curr) {
      if (next.indexOf('/store/item/') !== -1) {
        this.setState({
          selectedMenu: ['/store/item'],
          openMenu: openMenu.includes('item') ? openMenu : ['item'].concat(openMenu)
        })
      } else if (curr.indexOf('/record') < 0 && next.indexOf('/record/') !== -1) {
        this.setState({
          selectedMenu: [next],
          openMenu: [next].concat(openMenu)
        })
      } else if (next.indexOf('/item/modify') !== -1) {
        this.setState({
          selectedMenu: ['/item/schedule'],
          openMenu: openMenu.includes('item') ? openMenu : ['item'].concat(openMenu)
        })
      }
    }
    //清空商品主档页面缓存
    if(next === '/item/schedule' && curr.indexOf('/item/modify') === -1 && curr !== '/item/schedule') {
      this.props.itemStore.deleteCacheData()
    }
  }

  changeMenu = (path) => {
    //父子菜单对象，用来初始化激活菜单
    const menus = {
      '/index': [],
      "user": ["/user/info", "/user/auth", "/user/module"],
      "/shop": [],
      "/classify": [],
      "item": ["/item/schedule", "/item/store", "/item/modify", "/store/item", "/store/release", "/item/filter"],
      "record": ["/record/import", "/record/export"],
      "log": ["/log/shop", "/log/shopItem", "/log/category", "/log/inventory"],
      //"store": ["/store/item", "/store/release"],
      "/order": [],
      "/report/sales": []
    }
    let ifSub = false
    let currPath = path
    let openKey = []
    for (let v of Object.keys(menus)) {
      //menus[v] = [] 表示只有一级目录，无子目录
      if (menus[v].length === 0 && currPath === v) {
        ifSub = true
        openKey = menus[v]
        break
      } else if (menus[v].includes(currPath)) {
        ifSub = true
        openKey = [v]
        break
      }
    }
    return {
      openKey,
      ifSub
    }
  }

  toggle = () => {
    this.props.store.changeCollapse()
  }

  handleMenuOpen = (e) => {
    this.setState({
      openMenu: e
    })
  }

  handleMenuSelect = (e) => {
    if(this.props.location.pathname !== e.key) {
      this.setState({
        moduleId: e.item.props.moduleId,
        hasHelpMessage: false
      })
    }
    this.setState({
      selectedMenu: [e.key]
    })
  }

  handleRoutesFilter = (routePath) => {
    const {menu} = this.props.store;
    let flag = true;
    if(routePath.indexOf('/item/modify') !== -1) {
      return true;
    }
    menu.length > 0 && menu.every(item => {
    if(item.url === routePath) {
      flag = false;
    }
    if(item.children && item.children.length > 0) {
      flag = true;
      item.children.every(itemChildren => {
        if(itemChildren.url === routePath) {
          flag = false;
        }
        return flag;
      })
    }
    return flag
    })
    return !flag;
  }

  handleSetting = (e) => {
    const key = e.key
    const _this = this
    switch(key){
      case 'logout':
        confirm({
          title: '确定登出吗？',
          onOk() {
            window.localStorage.removeItem("riderMain")
            //window.location.href = '/login'
            _this.props.history.push('/login')
          },
          onCancel() {
            message.warning('取消登出！')
          },
        })
        break
      case 'changePwd':
        message.warning('修改密码功能未开放！')
        break
      default:
        break
    }
    
  }

  handleLocalChange = (e) => {
    this.props.store.changeLocale(e)
  }

 shopClick =  ({ key }) =>{
  const List = mobx.toJS(this.props.store.userCityList)
  // const shopList = List.find( v => v.shopList.shopId === key)
  const changeList = []
  List.forEach( data =>{
    const  list =data.shopList.find( v => v.shopId === key)
    if( list !== undefined){
      this.setState({
        shopName: list.shopNameAlias
      })
      this.props.store.changeShopId(list.shopId)
    }
  })
  }

  //打开帮助弹窗
  handleShowHelpModal = () => {
    const { getHelp, menu, clearHelp } = this.props.store;
    this.setState({
      visible: true
    })
    if(!this.state.hasHelpMessage ) {
      clearHelp();
      let moduleId = this.state.moduleId;
      if(moduleId === '') {
        let currPath = this.props.location.pathname
        if(currPath.indexOf('/item/modify') !== -1) {
          moduleId = 4001;
        } else {
          const getModuleId = (menu) => {
            menu.every(item => {
              if(item.url === currPath) {
                moduleId = item.moduleId;
                return false
              }
              if(item.children && item.children.length > 0) {
                getModuleId(item.children)
              }
              return true
            })
          }
          getModuleId(menu);
        }
      }
      getHelp(moduleId);
      this.setState({
        hasHelpMessage: true,
        moduleId: moduleId
      })
    }
  }

  //关闭帮助弹窗
  handleHideHelpModal = () => {
    this.setState({
      visible: false
    })
  }

  render() {
    const List = mobx.toJS(this.props.store.userCityList)
    const menuListData = mobx.toJS(this.props.store.menu)
    const NoMatch = ({location}) => (
      <div>
        <h2>No match for <code>{ location.pathname }</code></h2>
      </div>
    )
    const user = this.props.store.baseUser
    let userCom = ''
    if (user) {
      userCom = user.userName
    }
    const textButton = {
      border: 'none',
      color: 'rgba(255, 255, 255, 0.67)',
      background: 'transparent',
      paddingLeft: 0,
      paddingRight: 0,
    }

    const menuMatchData = {
      '首页': {icon: 'home'},
      '系统管理': {icon: 'usergroup-add', url: 'user'},
      '店铺管理': {icon: 'shop', url: 'shop'},
      '商品分类': {icon: 'appstore-o'},
      '商品管理': {icon: 'tags-o', url: 'item'},
      '记录查询': {icon: 'save', url: 'record'},
      '日志查询': {icon: 'file-text', url: 'log'},
      '订单管理': {icon: 'shopping-cart'},
      '销售报表': {icon: 'bar-chart'},
      '商品提报': {icon: 'bar-chart'}
    }

    return (
      <Layout style={ { height: '100%', display: 'flex', flexDirection: 'column'} }>
        <Header className="header" style={{height: 50, flex: '0 0 auto'}}>
          <Icon className="trigger" type={ this.props.store.collapse ? 'menu-unfold' : 'menu-fold' } onClick={ this.toggle } />
          <div className="logo">
            O2O
          </div>
          <div style={ { lineHeight: '50px', float: 'right',marginLeft:'20px' } }>
            <a href = "http://caozuoshouce.mydoc.io/" target="_Blank">
              <Icon type="download" style={{ fontSize: 14}}/>
              <span style={{lightHeight: '14px', paddingLeft: 3, fontSize: 12}}>操作手册</span>
            </a>
          </div>
          <div style={ { lineHeight: '50px', float: 'right',marginLeft:'20px' } }>
            <a onClick={this.handleShowHelpModal}>
              <Icon type="question-circle-o" style={{ fontSize: 14}}/>
              <span style={{lightHeight: '14px', paddingLeft: 3, fontSize: 12}}>帮助</span>
            </a>
          </div>
          {/* <div style={ { lineHeight: '50px', float: 'right' } }>
            <Button onClick={ () => this.handleLocalChange(this.props.store.locale.key) } ghost={true} style={ textButton }>{ this.props.store.locale.name }</Button>
          </div> */}
          <Menu theme="dark" mode="horizontal" selectedKeys={[]} onClick={ this.handleSetting } style={ { lineHeight: '50px', float: 'right' } }>
            <SubMenu title={ <span><Icon type="user" />{ userCom }</span> } >
              <Menu.Item key="logout">登出</Menu.Item>
              <Menu.Item key="changePwd">修改密码</Menu.Item>
            </SubMenu>
          </Menu>
        </Header>
        <Layout style={{flex: '1 0 auto', minHeight: 400}}>
          <Sider width={ 150 } style={ { background: '#fff' } } trigger={ null }
                 collapsible collapsed={ this.props.store.collapse }>
          <Menu mode="inline"
                openKeys={ this.state.openMenu }
                selectedKeys={ this.state.selectedMenu }
                onSelect={this.handleMenuSelect}
                onOpenChange={this.handleMenuOpen}
                style={ { height: '100%', borderRight: 0 } }>
            {menuListData.length > 0 && menuListData.map(item =>
              item.children && item.children.length > 0 ? (
                  <SubMenu key={item.url || menuMatchData[item.menuName].url }
                           title={ <span><Icon type={menuMatchData[item.menuName].icon} /><span>{item.menuName}</span></span> }>
                    {item.children.map(childrenItem =>
                      <Menu.Item key={childrenItem.url} moduleId={childrenItem.moduleId}>
                        <Link to={childrenItem.url}>{childrenItem.menuName}</Link>
                      </Menu.Item>
                    )}
                  </SubMenu>
              ) : (
                  <Menu.Item key={item.url} moduleId={item.moduleId}>
                    <Link to={item.url}><span><Icon type={menuMatchData[item.menuName].icon} /><span>{item.menuName}</span></span>
                    </Link>
                  </Menu.Item>
              )
            )}
            </Menu>
          </Sider>
          <Layout style={ { padding: '0 0 0px 6px', width: 100 } }>
            <Content style={ { background: '#fff', padding: '16px 16px 16px 16px', margin: 0 } }>
              <Switch>
                <Redirect exact={ true } from='/' to='/login' />
                <Redirect exact={ true } from='/**/*.html' to='/index' />
                {menuListData.length > 0 && routes.map((route, index) => (
                  route.path === 'notMatch' ? <Route key={ index } component={ NoMatch } /> :
                  this.handleRoutesFilter(route.path) &&
                    <Route key={ index } path={ route.path } exact={ route.exact } component={route.component} />
                  )) }
                { /* <Redirect exact={true} to='/index'/> */ }
                {/*<Route component={ NoMatch } />*/}
              </Switch>
            </Content>
          </Layout>
        </Layout>
        <Modal visible={this.state.visible} title="帮助文档" width={'95%'}
            onCancel={this.handleHideHelpModal}
            footer={[
            <Button key="back" size="large" type="primary" onClick={this.handleHideHelpModal}>关闭</Button>,
          ]}>
          <Spin spinning={this.props.store.helpLoading}>
            <div className='ql-editor help-module' dangerouslySetInnerHTML={{__html: this.props.store.helpMessage}} />
          </Spin>
        </Modal>
      </Layout>
    )
  }
}
export default localeFn(App)